import axios from "axios";
import type {
  AxiosInstance,
  AxiosResponse,
  AxiosError,
  InternalAxiosRequestConfig,
} from "axios";
import { handleSSO, errorMsgTips } from "@/utils/func";

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_USE_MOCK
    ? import.meta.env.VITE_APP_MOCK_BASEURL
    : import.meta.env.VITE_APP_API_BASEURL,
  timeout: 60000,
});

// axios实例拦截请求
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers["X-Requested-With"] = "XMLHttpRequest";
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

// axios实例拦截响应
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const resData = response.data || {};

    if (resData.code === 58302) {
      window.location.href = `https://auth.58.com/58shieldlogin.html?domain=${
        location.host
      }&req=${encodeURIComponent(location.pathname)}&protocol=https${location.hash}`;
    } else if (resData.code === 0 || resData.code === 200) {
      return resData;
    } else {
      errorMsgTips(resData.message || "接口错误，请稍后重试");
    }
    // return response;
  },
  (error: any) => {
    if (error && error.response && error.response.status === 302) {
      if (process.env.NODE_ENV === "development") {
        errorMsgTips("请替换Cookies里的SSO_SESSION_ID");
        return;
      } else {
        window.location.href = handleSSO("login");
      }
    } else if (error && error.stack.includes("timeout")) {
      errorMsgTips("接口超时");
      return;
    } else if (error && error.stack.includes("Network")) {
      errorMsgTips("网络异常");
      return;
    }

    return Promise.reject(error);
  },
);

export default service;
